include include.mk

includePATH = include
buildPATH 	= build

SOURCE_FILES := $(shell find -name "*.[cS]" -not -path "./rinos-usr/*")
OBJS := $(patsubst ./%, $(buildPATH)/%.o, $(SOURCE_FILES))

all: build

$(buildPATH)/%.c.o: %.c
	@mkdir -p $(@D)
	@echo " BUILD: $<"
	@$(CC) $(CFLAG) -I$(includePATH) $< -o $@

$(buildPATH)/%.S.o: %.S
	@mkdir -p $(@D)
	@echo " BUILD: $<"
	@$(AS) $(ASFLAG) -I$(includePATH) $< -o $@

kernel.bin: $(OBJS)
	@echo " BUILD: $@"
	@$(LD) $(LDFLAG) $+ -o $(buildPATH)/$@

clean:
	@rm -rf ./build ./*/*.o kernel.dbg

image: kernel.bin
	@mkdir -p disk
	@mkdir -p disk/boot
	@mkdir -p disk/boot/grub
	@cp -n backups/grub.cfg disk/boot/grub/
	@cp $(buildPATH)/kernel.bin disk/boot/
	@grub-mkrescue -o disk.iso disk/

run:
	@qemu-system-i386 $(QEMU_OPTIONS_NONDEBUG)
	@sleep 0.5
	@telnet 127.0.0.1 $(QEMU_MON_PORT)

run-bochs:
	@bochs -f ./backups/bochs.cfg

debug: CFLAG += -g -D__DEBUG__
debug: ASFLAG += -g
debug: LDFLAG += -g
debug: build
	@objcopy --only-keep-debug $(buildPATH)/kernel.bin kernel.dbg

debug-qemu: debug
	@qemu-system-i386 $(QEMU_OPTIONS)
	@sleep 1
	@$(QEMU_MON_TERM) -- telnet 127.0.0.1 $(QEMU_MON_PORT)
	@gdb -s kernel.dbg -ex "target remote localhost:1234"

debug-qemu-vscode: debug
	@qemu-system-i386 $(QEMU_OPTIONS)
	@sleep 0.5
	@telnet 127.0.0.1 $(QEMU_MON_PORT)

debug-qemu-vscode-no-rebuild:
	@qemu-system-i386 $(QEMU_OPTIONS)
	@sleep 0.5
	@telnet 127.0.0.1 $(QEMU_MON_PORT)

build: clean image
	@echo Done!!!
